package com.cincc.cincc_pbx.common;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.cincc.cincc_pbx.R;
import com.cincc.cincc_pbx.common.callback.IDialogCallback;
import com.cincc.cincc_pbx.constant.CallConstant;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

public class MyUtils {

    //获取验证码图片
    public static Map<String, Bitmap> getImage(String path) throws Exception {
        Map<String, Bitmap> map = new HashMap<>();
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if (path.startsWith("https")) {
            HttpsURLConnection https = (HttpsURLConnection) conn;
            HttpUtils.trustAllHosts(https);
            https.setHostnameVerifier(HttpUtils.DO_NOT_VERIFY);
        }
        if (conn.getResponseCode() == 200) {
            InputStream inStream = conn.getInputStream();
            String key = conn.getHeaderField("verifyKey");
            Bitmap bitmap = BitmapFactory.decodeStream(inStream);
            map.put(key, bitmap);
            return map;
        }
        return null;
    }

    //给密码加密
    public static String encodePassword(String data) {
        String md5 = MD5Util.encrypt(data);
        return AesUtils.encrypt(md5, CallConstant.AES_PASSWORD_KEY);
    }

    public static String getNumber(int index) {
        if (index <= 8) {
            return (index + 1) + "";
        } else if (index == 9) {
            return "*";
        } else if (index == 10) {
            return "0";
        } else {
            return "#";
        }
    }

    public static void showConfirmDialog(Activity context, String contentStr, IDialogCallback callback) {
        AlertDialog userDialog = new AlertDialog.Builder(context).create();
        View view = LayoutInflater.from(context).inflate(R.layout.confirm_dialog, null);
        TextView title = view.findViewById(R.id.tv_title);
        TextView content = view.findViewById(R.id.tv_content);
        TextView cancel = view.findViewById(R.id.tv_cancel);
        TextView confirm = view.findViewById(R.id.tv_confirm);
        content.setText(contentStr);
        cancel.setOnClickListener(v -> {
            callback.cancel();
            userDialog.dismiss();
        });
        confirm.setOnClickListener(v -> {
            callback.confirm();
            userDialog.dismiss();
        });
        userDialog.show();
        userDialog.setCancelable(true);
        Window window = userDialog.getWindow();
        window.setBackgroundDrawableResource(android.R.color.transparent);
        window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        WindowManager.LayoutParams lp = window.getAttributes();
        Display display = context.getWindowManager().getDefaultDisplay();
        lp.width = (int) (display.getWidth() * 0.8);
        window.setAttributes(lp);
        // 设置显示视图内容
        window.setContentView(view);
    }

    public static String getCurrentTimeStr() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        Date curDate = new Date(System.currentTimeMillis());
        return formatter.format(curDate);
    }

    public static String getCurrentMonthTimeStr() {
        // 获取当前日历实例
        Calendar calendar = Calendar.getInstance();
        // 获取当前年份
        int year = calendar.get(Calendar.YEAR);
        // 获取当前月份（月份从0开始，所以需要加1）
        int month = calendar.get(Calendar.MONTH) + 1;
        String monthStr = month < 10 ? ("0" + month) : String.valueOf(month);
        return year + monthStr + "01000000";
    }

    public static String convertSecondsToHMS(int seconds) {
        int hours = seconds / 3600;
        int minutes = (seconds % 3600) / 60;
        int remainingSeconds = seconds % 60;

        if (hours > 0) {
            return hours + "小时 " + minutes + "分" + remainingSeconds + "秒";
        } else if (minutes > 0) {
            return minutes + "分" + remainingSeconds + "秒";
        } else {
            return remainingSeconds + "秒";
        }
    }

    /**
     * 获取注册分机号
     * 如果在登录页填了分机号，则 注册分机号格式为GROUP_ID+企业号+登录页填写的分机号
     * 如果在登录页没有填写分机号，则 注册分机号是从接口获取的
     *
     * @return
     */
    public static String getSipAccount() {
        String sipAccount = "";
        if (CallConstant.loginModel.getExtension().length() > 0) {
            sipAccount = CallConstant.GROUP_ID + CallConstant.loginModel.getVccId() + CallConstant.loginModel.getExtension();
        } else {
            sipAccount = CallConstant.loginModel.getTelPhone();
        }
        return sipAccount;
    }

    public static String convertSecondsToTime(int seconds) {
        int hours = seconds / 3600;
        int minutes = (seconds % 3600) / 60;
        int remainingSeconds = seconds % 60;
        if (hours > 0) {
            return String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes, remainingSeconds);
        } else {
            return String.format(Locale.getDefault(), "%02d:%02d", minutes, remainingSeconds);
        }
    }
}